import { useEffect, useMemo, useRef, useState } from "react";
import { Table, Divider, Button, message, Modal, Flex, Typography, Space, Tag } from "antd";
import { keepPreviousData, useQueries, useQuery } from "@tanstack/react-query";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, EyeOutlined, DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { download } from "@/utils";
import { m } from "framer-motion";
import { Link } from "react-router-dom";
import { useDictionary } from "@/hooks";
import styled from 'styled-components'
import { useThemeToken } from "@/theme/hooks";
import SearchForm from "@/components/searchForm";
import SelectCatalogTree from "./modules/SelectCatalogTree";
import DataResourceForm from "./modules/DataResourceForm";
import {
  dataResourcePage,
  dataResourceUpdate,
  dataResourceDelete
} from "@/api/sharing/dataCatalog";
import DisplayLabel from "@/components/displayLabel";

const queryItems = [
  {
    name: 'resourceName',
    label: '资源名称',
    type: 'INPUT',
  }
];


const SliderTrigger = ({ onChange, value }) => {
  const { colorBorder, colorBgBase } = useThemeToken()
  const StyledDiv = styled.div`
  position: absolute;
  width: 20px;
  height: 30px;
  top: 7px;
  right: -19px;
  text-align: center;
  line-height: 30px;
  border: ${colorBorder} solid 1px;
  background-color: ${colorBgBase};
  border-width: '1px 1px 1px 0';
  cursor: pointer;
`
  return (
    <StyledDiv
      onClick={() => onChange(!value)}
    >
      {value ? <DoubleLeftOutlined /> : <DoubleRightOutlined />}
    </StyledDiv >
  )
}



//i18n
const DataCatalogIndex = () => {
  // useDictionary(['data_resource_access_Type'])
  const { colorBorder } = useThemeToken();
  const [queryParam, setQueryParam] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [sliderShow, setSliderShow] = useState(true)
  const [parentNode, setParentNode] = useState()
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      key: "no",
      title: "序号",
      width: 50,
      render(text, _, index) {
        return (page.pageNo - 1) * page.pageSize + index + 1;
      }
    },
    // {
    //   dataIndex: "appName",
    //   title: "应用名称",
    //   width: 120
    // },
    {
      dataIndex: "resourceName",
      title: "数据资源名称",
      width: 120
    },

    {
      dataIndex: "catalogName",
      title: "类型",
      width: 100,
      render: (text) => (<Tag>{text}</Tag>)
    },
    {
      dataIndex: "accessType",
      title: "访问方式",
      width: 100,
    },
    // {
    //   dataIndex: "describe",
    //   title: "发布状态",
    //   width: 120
    // },
    {
      dataIndex: "resourceSign",
      title: "标识",
      width: 120
    },
    {
      dataIndex: "remark",
      title: "描述",
      width: 120
    },
    {
      dataIndex: "publishTime",
      title: "发布时间",
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>编辑</a>}
            title={`编辑-` + record.resourceName}
            modalProps={{ destroyOnClose: true }}
            initialValues={{
              ...record
            }}
            width={'400px'}
            grid={true}
            onFinish={saveData}
          >
            <DataResourceForm />
          </ModalForm>
          <Divider type="vertical" />
          <Link to={`/integration/sharing/dataCatalog/${record.businessId}`}><EyeOutlined /> 详情</Link>
          <Divider type="vertical" />
          <Link to={`/integration/sharing/dataCatalog/${record.businessId}/tryout`}>测试</Link>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-dataCatalog-dataResourcePage', queryParam, page],
    queryFn: () => {
      return dataResourcePage({
        pageNo: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam
      }).then((res) => {
        return res.result || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }
  const saveData = (values) => {
    if (values.id) {
      return dataResourceUpdate(values).then((res) => {
        if (res.code !== 200) return
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return true
      // return dataCatalogImport(values).then(() => {
      //   refetch()
      //   message.success('新增成功')
      //   return true
      // })
    }
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return dataResourceDelete({ id: ids })
          .then((res) => {
            if (res.code === 200) {
              onSelectChange([], [])
              refetch()
              message.success('删除成功')
            }
          })
      },
      onCancel() { },
    });
  };

  const onTreeChange = (value, info) => {
    setQueryParam({
      ...queryParam,
      catalogId: value[0] || undefined
    })

    setParentNode(info.selected ? info.node : undefined)
  }


  return (
    <StyleWrapper>
      <m.div
        className="tree-wrapper"
        style={{ borderRight: `1px solid ${colorBorder}`, flexShrink: 0 }}
        animate={sliderShow ? "open" : "closed"}
        variants={{
          open: {
            left: 0,
            transition: {
              type: "tween",
              duration: 0.3,
            },
          },
          closed: {
            left: '-220px',
            transition: {
              type: "tween",
              duration: 0.3,
            },
          },
        }}
      >
        <SelectCatalogTree
          showSearch
          selectedKeys={[queryParam.catalogId]}
          onSelect={onTreeChange} />
        <SliderTrigger value={sliderShow} onChange={setSliderShow} />
      </m.div>

      <m.div
        className="table-wrapper"
        animate={sliderShow ? "open" : "closed"}
        variants={{
          open: {
            marginLeft: '220px',
            transition: {
              type: "tween",
              duration: 0.3,
            },
          },
          closed: {
            marginLeft: '0',
            transition: {
              type: "tween",
              duration: 0.3,
            },
          },
        }}
      >
        <div className="searchTableHeader">数据目录</div>
        <SearchForm
          onSearch={(values) => {
            if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
              setQueryParam({ ...values })
            } else {
              refetch()
            }
          }}
          items={queryItems}
          searchContent="查询"
        />
        <Table
          rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
          columns={columns}
          rowKey={(record) => record.id}
          loading={isFetching}
          dataSource={tableData?.list || []}
          pagination={{
            current: page.pageNo,
            pageSize: page.pageSize,
            total: tableData?.total,
            onChange: (pageNo, pageSize) => {
              setPage({ pageNo, pageSize })
            }
          }}
        />
      </m.div>
    </StyleWrapper>
  );
};


const StyleWrapper = styled.div`
height: 100%;
position: relative;
.tree-wrapper{
  height: calc(100% - 63px);
  position: fixed;
  top: 63px;
  z-index: 5;
  width: 220px;
  padding-top: 16px;

}
.table-wrapper{
  padding: 12px 20px;
  position: relative;
  margin-left: 220px;
  display: flex;
  flex-direction: column;
}
`

export default DataCatalogIndex;
